// 电梯状态变量
const elevatorState = {
  currentFloor: 1,       // 当前楼层
  targetFloor: 1,        // 目标楼层
  isMoving: false,       // 是否正在移动
  doorsOpen: false,      // 门是否打开
  requestQueue: []       // 请求队列
};

// DOM元素
let elevatorCab, elevatorDoors, currentFloorDisplay;
let floorButtons, openDoorBtn, closeDoorBtn;
let elevatorStatusText, sendCommandBtn;
let elevatorSelect, targetFloorSelect;
let statusFloor, statusRunning, statusDoors;

// 初始化电梯控制
document.addEventListener('DOMContentLoaded', function() {
  // 获取DOM元素
  elevatorCab = document.getElementById('elevatorCab');
  elevatorDoors = document.getElementById('elevatorDoors');
  currentFloorDisplay = document.getElementById('currentFloorDisplay');
  floorButtons = document.querySelectorAll('.floor-btn, .quick-floor-btn');
  openDoorBtn = document.getElementById('openDoorBtn');
  closeDoorBtn = document.getElementById('closeDoorBtn');
  openGateBtn = document.getElementById('openGateBtn');
  closeGateBtn = document.getElementById('closeGateBtn');

  elevatorStatusText = document.getElementById('elevatorStatusText');
  sendCommandBtn = document.getElementById('sendCommandBtn');
  elevatorSelect = document.getElementById('elevatorSelect');
  targetFloorSelect = document.getElementById('targetFloorSelect');
  
  // 状态显示元素
  statusFloor = document.getElementById('statusFloor');
  statusRunning = document.getElementById('statusRunning');
  statusDoors = document.getElementById('statusDoors');
  
  // 绑定事件监听
  bindEvents();
  
  // 初始化状态显示
  updateStatusDisplay();
});

// 绑定事件
function bindEvents() {
  // 楼层按钮点击事件
  floorButtons.forEach(button => {
    button.addEventListener('click', () => {
      const targetFloor = button.dataset.floor;
      // requestFloor(targetFloor);
      set_elevatordoor(targetFloor)
      
      // 更新下拉选择框
      targetFloorSelect.value = targetFloor;
    });
  });
  // 开门关门按钮
  openDoorBtn.addEventListener('click', () => set_elevatordoor("open"));
  closeDoorBtn.addEventListener('click', () => set_elevatordoor("close"));
  openGateBtn.addEventListener('click', () => set_elevatordoor("opengate"));
  closeGateBtn.addEventListener('click', () => set_elevatordoor("closegate"));
  // 发送指令按钮
  sendCommandBtn.addEventListener('click', () => {
    const selectedElevator = elevatorSelect.value;
    const targetFloor = targetFloorSelect.value;
    // 对于1号和2号电梯，我们只演示动画电梯的响应
    if (selectedElevator === '1' || selectedElevator === '2') {
      set_elevatordoor(targetFloor);
    }
  });
}

// 更新状态显示
function updateStatusDisplay() {
  if (!statusFloor || !statusRunning || !statusDoors) return;
  statusFloor.textContent = `${elevatorState.currentFloor}F`;
  currentFloorDisplay.textContent = `${elevatorState.currentFloor}F`;
  statusRunning.textContent = elevatorState.isMoving ? '运行中' : '静止';
  statusDoors.textContent = elevatorState.doorsOpen ? '打开' : '关闭';
  // 更新电梯状态标签
  if (elevatorState.isMoving) {
    elevatorStatusText.textContent = '运行中';
    elevatorStatusText.className = 'px-3 py-1 bg-success/10 text-success text-xs rounded-full';
  } else if (elevatorState.doorsOpen) {
    elevatorStatusText.textContent = '门打开';
    elevatorStatusText.className = 'px-3 py-1 bg-warning/10 text-warning text-xs rounded-full';
  } else {
    elevatorStatusText.textContent = '待命';
    elevatorStatusText.className = 'px-3 py-1 bg-primary/10 text-primary text-xs rounded-full';
  }
}

function set_elevatordoor (state) {
  fetch('/api/setElevatorDoor', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: state,  // 前端传递的状态字段
    })
  })
  .then(response => response.json())
  .then(res => console.log('后端响应：', res))
  .catch(err => console.error('请求失败：', err));
}

// 打开电梯门
function openDoors() {
  if (elevatorState.isMoving) return; // 移动中不能开门
  set_elevatordoor("open")
  elevatorDoors.classList.add('doors-open');
  elevatorState.doorsOpen = true;
  updateStatusDisplay();
}

// 关闭电梯门
function closeDoors() {
  if (elevatorState.isMoving) return; // 移动中不能关门
  set_elevatordoor("close")
  elevatorDoors.classList.remove('doors-open');
  elevatorState.doorsOpen = false;
  updateStatusDisplay();
}

// 移动到指定楼层
function moveToFloor(targetFloor) {
  
  // 如果已经在目标楼层或正在移动，直接返回
  if (elevatorState.currentFloor === targetFloor || elevatorState.isMoving) {
    return;
  }
  set_elevatordoor(targetFloor)
  // 如果门是打开的，先关门再移动
  if (elevatorState.doorsOpen) {
    // closeDoors();
    // 等待门关闭后再移动
    setTimeout(() => {
      actuallyMoveToFloor(targetFloor);
    }, 1500); // 等待门关闭动画完成
  } else {
    actuallyMoveToFloor(targetFloor);
  }
}

// 实际执行移动的函数
function actuallyMoveToFloor(targetFloor) {
  elevatorState.isMoving = true;
  elevatorState.targetFloor = targetFloor;
  updateStatusDisplay();
  // 更新按钮状态
  updateButtonStates();
  // 计算目标位置 (每层高度180px)
  const targetPosition = (1 - targetFloor) * 180;
  // 应用移动动画
  elevatorCab.style.transform = `translateY(${targetPosition}px)`;
  // 移动完成后更新状态
  setTimeout(() => {
    elevatorState.currentFloor = targetFloor;
    elevatorState.isMoving = false;
    // // 打开门
    // openDoors();
    // 更新状态显示
    updateStatusDisplay();
    // 更新按钮状态
    updateButtonStates();
    
    // 处理下一个请求
    processNextRequest();
  }, 3000); // 移动动画持续时间
}

// 添加楼层请求
function requestFloor(floor) {
  // 转换为数字
  floor = parseInt(floor);
  // 只处理1-3层，因为动画电梯只有3层
  if (floor < 1 || floor > 3) {
    // 对于高层，可以显示提示信息
    alert('动画演示电梯仅支持1-3层');
    return;
  }
  
  // 如果已经在请求队列中，不再添加
  if (elevatorState.requestQueue.includes(floor)) {
    return;
  }
  // 如果当前没有移动，直接前往目标楼层
  if (!elevatorState.isMoving && elevatorState.currentFloor !== floor) {
    elevatorState.requestQueue = [floor];
    moveToFloor(floor);
  } 
  // 否则添加到队列
  else if (elevatorState.currentFloor !== floor) {
    elevatorState.requestQueue.push(floor);
  }
  // 更新按钮状态
  updateButtonStates();
}

// 处理下一个请求
function processNextRequest() {
  // 移除当前楼层的请求
  elevatorState.requestQueue = elevatorState.requestQueue.filter(floor => floor !== elevatorState.currentFloor);
  
  // 如果还有请求，处理下一个
  if (elevatorState.requestQueue.length > 0) {
    // 等待门打开一段时间后再关闭并前往下一楼层
    setTimeout(() => {
      // closeDoors();
      setTimeout(() => {
        moveToFloor(elevatorState.requestQueue[0]);
      }, 700); // 等待门关闭
    }, 2000); // 门打开后停留2秒
  }
}

// 更新按钮状态
function updateButtonStates() {
  floorButtons.forEach(button => {
    const floor = parseInt(button.dataset.floor);
    
    // 如果是当前楼层或在请求队列中，高亮显示
    if (floor === elevatorState.currentFloor || elevatorState.requestQueue.includes(floor)) {
      button.classList.add('active');
    } else {
      button.classList.remove('active');
    }
  });
}